package com.fast.alden.admin.web.controller.config;

import com.fast.alden.admin.util.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Spring Web MVC Bean配置
 * 全局配置允许跨域；
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 文件上传存储路径
     */
    @Value("${fast-alden.file.local.upload-path}")
    private String uploadPath;
    /**
     * 访问已上传文件URL前缀
     */
    @Value("${fast-alden.file.local.upload-access-prefix}")
    private String uploadAccessPrefix;

    /**
     * 解决跨域问题，security配置中还需启用cors()
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    /**
     * 为所有Controller配置统一前缀
     *
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix("/api/v1.0/admin", c -> (c.getPackage().getName().startsWith(Constants.CONTROLLER_PACKAGE_NAME_PREFIX))
                && (c.isAnnotationPresent(Controller.class) || c.isAnnotationPresent(RestController.class)));
    }

    /**
     * 文件 url 映射
     * 配置server虚拟路径，handler为前台访问的目录，locations为files相对应的本地路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(uploadAccessPrefix + "**").addResourceLocations("file:" + uploadPath);
    }
}
